import itertools
import re

def powerset(xs):
    return itertools.chain.from_iterable(itertools.combinations(xs, r) for r in range(len(xs) + 1))

with open('input.txt') as file:
    memory = {}
    or_mask = 0
    and_mask = 0

    for line in file.read().splitlines():
        if line.startswith('mask'):
            mask = re.fullmatch(r'mask = ([X10]{36})', line).groups()[0]

            or_mask =  int(mask.replace('X', '0'), 2)
            and_mask = int(mask.replace('0', '1').replace('X', '0'), 2)

            floating = [35 - i for (i, c) in enumerate(mask) if c == 'X']
        else:
            address, value = map(int, re.fullmatch(r'mem\[(\d+)\] = (\d+)', line).groups())
            
            address &= and_mask
            address |= or_mask
            
            for comb in powerset(floating):
                new_address = address
                for i in comb:
                    new_address |= (1 << i)
                memory[new_address] = value
                
    print(sum(memory.values()))